package com.hjk.common.aop.aspect;

import com.hjk.common.utils.web.IPUtils;
import com.hjk.common.model.vo.KafkaCountTime;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 统计方法的执行时间注解
 * @author huangjunkai
 * @version 1.0
 * @date 2020/5/5 3:50
 */

@Aspect
@Component
@Slf4j
public class CountTimeAspect {

    // 定义切点Pointcut
    @Pointcut("@annotation(com.hjk.common.aop.annotation.CountMethodTimeLog)")
    public void countMethodTimeCut() {

    }

    @Around("countMethodTimeCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        assert sra != null;
        //获取request对象
        HttpServletRequest request = sra.getRequest();
        //请求url http://localhost:9750/send
        String url = request.getRequestURL().toString();
        //请求方式 get post put  等等
        String method = request.getMethod();
        //请求uri  /send
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        log.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);

        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = pjp.proceed();
        //执行时长(毫秒)
        long time =  ((System.currentTimeMillis() - beginTime));


        //获取请求方法各个参数
        MethodSignature signature = (MethodSignature)pjp.getSignature();

        //获取执行方法的全限定类名 com.hjk.技术demo.消息队列.kafka.controller.SendMessageController
        String className = pjp.getTarget().getClass().getName();

        //获取执行的方法名  sendMessage
        String methodName = signature.getName();

        //请求的参数
        Object[] args = pjp.getArgs();
        String params = args[0].toString();

        //获取ip
        String ipAddr = IPUtils.getIpAddr(request);


        log.info("方法{} 执行了{}毫秒",className+"."+methodName,time);

        KafkaCountTime kafkaCountTime = new KafkaCountTime();
        kafkaCountTime.setTimes(time);
        kafkaCountTime.setFully(className+"."+methodName);
        kafkaCountTime.setCounts(Long.parseLong(params));
        kafkaCountTime.insert();
        return result;
    }
}
